package com.jackstraw.jack_base.datasource.jpa.base.dao.aspect.contextholder;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.jackstraw.jack_base.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.EntityManager;

@Slf4j
public class BaseDaoContextholder {

    private final static ThreadLocal<EntityManager> entityManagerThreadLocal = new TransmittableThreadLocal<>();

    public static EntityManager getEntityManager() {
        return entityManagerThreadLocal.get();
    }


    public static void setEntityManager(EntityManager entityManager) {
        entityManagerThreadLocal.set(entityManager);
        log.debug("JPA->Hibernate open connection...");
    }

    public static void clearEntityManager() {
        try {
            EntityManager entityManager = entityManagerThreadLocal.get();
            if (ObjectUtil.ObjectUtilByLang3.isNotEmpty(entityManager) && entityManager.isOpen()) {// 关闭连接
                entityManager.close();
                log.debug("JPA->Hibernate close connection...");
            }
        } finally {
            entityManagerThreadLocal.remove();
        }
    }
}
